import React, {useState, useEffect} from 'react';
import {Button, Divider, Space, Table, Modal, Tag} from 'antd';
import {ColumnsType} from "antd/lib/table";
import styles from './index.module.scss';
import {IPageResponse, IParam, statusEnum} from "@/common/common";
import {apiGetUserList} from "@/apis/user";
import {ExclamationCircleOutlined, PlusOutlined} from "@ant-design/icons";
import UpdateUserForm from "@/pages/system/user/components/UpdateUserForm";
import {UserListItem} from "@/pages/system/user/constant";
import CreateUserForm from "@/pages/system/user/components/CreateUserForm";

const {confirm} = Modal;

const TableList: React.FC<any> = () => {

  const [row, setRow] = useState<UserListItem>();
  const [selectedRowsState, setSelectedRows] = useState<UserListItem[]>([]);

  const [loading, setLoading] = useState<boolean>(false);
  const [params, setParams] = useState<IParam>({page: 1, size: 10});
  const [createModalVisible, setCreateModalVisible] = useState<boolean>(false);
  const [updateModalVisible, setUpdateModalVisible] = useState<boolean>(false);
  const [editFormValues, setEditFormValues] = useState<Partial<UserListItem>>({});
  const [pageResponse, setPageResponse] = useState<IPageResponse<any>>({pageInfo: {page: 1, size: 10, total: 0}})

  useEffect(() => {
    setLoading(true);
    apiGetUserList(params, true).then(res => {
      setPageResponse(res);
    }).finally(() => setLoading(false));
  }, [params]);

  const columns: ColumnsType<any> = [
    {
      title: '用户名',
      key: 'userName',
      dataIndex: 'userName',
      align: "center",
    },
    {
      title: '昵称',
      key: 'nickName',
      dataIndex: 'nickName',
      align: "center",
    },
    {
      title: '手机号',
      key: 'mobile',
      dataIndex: 'mobile',
      align: "center",
    },
    {
      title: '邮箱',
      key: 'email',
      dataIndex: 'email',
      align: "center",
    },
    {
      title: '部门',
      key: 'deptName',
      dataIndex: 'deptName',
      align: "center",
    },
    {
      title: '职位',
      key: 'jobName',
      dataIndex: 'jobName',
      align: "center",
    },
    {
      title: '角色',
      key: 'roleName',
      dataIndex: 'roleName',
      align: "center",
    },
    {
      title: '状态',
      key: 'status',
      dataIndex: 'status',
      align: "center",
      render: (value: string, record: any) => {
        const element = statusEnum[value]
        return element && <Tag color={element.color} key={record.id}>{element.text}</Tag>
      }
    },
    {
      title: '操作',
      key: 'option',
      dataIndex: 'option',
      align: "center",
      render: (text: any, record: any) => (
        <>
          <Button
            type="primary"
            size="small"
            onClick={() => {
              setUpdateModalVisible(true);
              setEditFormValues(record);
            }}
          >
            编辑
          </Button>
          <Divider type="vertical"/>
          <Button
            type="primary"
            danger
            size="small"
            onClick={() => {
              showDeleteConfirm([record.id]);
            }}
          >
            删除
          </Button>
        </>
      )
    },
  ]

  const showDeleteConfirm = (ids: number[]) => {
    confirm({
      title: '是否删除记录?',
      icon: <ExclamationCircleOutlined/>,
      content: '删除的记录不能恢复,请确认!',
      onOk() {
        // handleRemoveOne(id).then((r) => {
        //   actionRef.current?.reloadAndRest?.();
        // });
      },
      onCancel() {
      },
    });
  }

  const renderToolBar = () => {
    return (
      <Space size={10}>
        <Button type="primary" onClick={() => setCreateModalVisible(true)}>
          <PlusOutlined/> 新建用户
        </Button>
      </Space>
    )
  }

  return (
    <div className={styles.container}>
      <div className={styles.toolBar}>{renderToolBar()}</div>
      <Table
        rowKey={"id"}
        columns={columns}
        dataSource={pageResponse.data || []}
        pagination={{
          current: pageResponse.pageInfo.page || 0,
          pageSize: pageResponse.pageInfo.size || 10,
          showQuickJumper: true,
          showSizeChanger: true,
          pageSizeOptions: ["10", "20", "30"],
          total: pageResponse.pageInfo.total || 0,
          showTotal: (total) => `共 ${total} 条`,
          onChange: (pageNo, pageSize) => {
            setParams({...params, ...{page: pageNo, size: pageSize}})
          }
        }}
      />

      <CreateUserForm
        key={'CreateUserForm'}
        createModalVisible={createModalVisible}
        onCancel={() => {
          setCreateModalVisible(false);
          setEditFormValues({});
        }}
        onSubmit={async (value) => {
          // const success = await handleAdd(value);
          setCreateModalVisible(false);
          setEditFormValues({});
        }}
      />

      <UpdateUserForm
        key={'UpdateUserForm'}
        updateModalVisible={updateModalVisible}
        currentData={editFormValues}
        onCancel={() => {
          setUpdateModalVisible(false);
          setEditFormValues({});
        }}
        onSubmit={async (value) => {
          // const success = await handleUpdate(value);
          setUpdateModalVisible(false);
          setEditFormValues({});
        }}
      />
    </div>
  )
}

export default TableList
